<template>
	<view class="main">
		<!-- <u-navbar
			title="巡检任务"
			:autoBack="false"
			bgColor="#FF5000"
			:placeholder="true"
			back-icon-color="#FFFFFF"
			:title-style="{fontSize:'16px', fontFamily:'PingFang SC', fontWeight:'600', color:'#FFFFFF'}">
			<view class="u-nav-slot" slot="left">
			    <u--image :src="returnUrl" @click.native="returnPage" width="9px" height="16px" style="margin-top: 2px;"></u--image>
			  </view>
			<view class="u-nav-slot" slot="right">
				<u--image :src="startUrl" @click.native="urlStatus" width="20px" height="20px" style="margin-top: 2px;"></u--image>
			</view>
		</u-navbar> -->
		<view class="mid">
			<view class="top"
				style="margin-top: 12px;margin-left: 16px;margin-right:16px;display:flex;justify-content: space-between;">
				<view>
					<text style="font-size: 14px;color: #999999;font-family: 'PingFang SC';">巡检情况</text>
				</view>
				<view>
					<u-radio-group :disabled="radioSwitch" v-model="radioStatus" activeColor="#FF5000">
						<u-radio :name="0">正常</u-radio>
						<u-radio :name="1" style="margin-left: 10px;">异常</u-radio>
					</u-radio-group>
				</view>
			</view>
			<div style="margin-top: 12px;">
				<u-line></u-line>
			</div>
			<view class="mid" style="margin-top: 16px;margin-left: 16px;">
				<text style="font-size: 14px;color: #999999;font-family: 'PingFang SC';">巡检内容</text>
				<u--textarea v-model="resultText" :disabled="textSwitch" placeholder="此处输入信息" count height="105px"
					maxlength='2000' style="margin-top: 8px;margin-right: 16px;"></u--textarea>
			</view>
			<div style="margin-top: 10px;">
				<u-line></u-line>
			</div>
			<view class="bottom" style="margin-top: 17px;margin-left: 16px;">
				<text style="font-size: 14px;color: #999999;font-family: 'PingFang SC';">现场照片</text>
				<view style="border: 0.5px solid #979797;width: 95%;height: 72px;margin-top: 8px;display: flex;">
					<view class="aaa" style="display: flex;" v-for="(item,index) in fileTempList" :key="index">
						<view style="position: relative; margin-top: 8px; margin-left: 8px;">
							<u--image :src="item.url" width="55px" height="55px"></u--image>
							<u-icon name="close" style="position: absolute; top: 2px; right: 2px;"
								@click="removeItem(index)"></u-icon>
						</view>
					</view>
					<u--image :src="upLoadUrl" v-show="fileTempList.length<5" width="55px" height="55px"
						style="margin-top: 8px;margin-left: 8px;" @click="getFile"></u--image>
				</view>
			</view>
			<view class="btn" style="margin-top: 24px;margin-left: 16px;margin-right: 16px;">
				<u-button v-if="addRecord.id===''" text="开始" @click="start" color="#FF5000"
					style="border-radius: 4px;" :loading="loading"></u-button>
				<u-button v-if="addRecord.id!==''" text="提交" @click="submit" color="#FF5000"
					style="border-radius: 4px;" :loading="loading"></u-button>
				<u-button text="取消" @click="returnPage" color="#FF5000" plain
					style="margin-top: 8px;border-radius: 4px;"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import croods from '@/common/croods-1.3.3.js';
	window.croods = croods;
	window.hydra = require('../../../common/wst_hydra-1.0.0.js');


	import coordtransform from 'coordtransform';
	import {
		editXJRecord,
		addtrack,
		addXJRecord,
		uploadFile
	} from "@/common/api.js"
	export default {
		onLoad: function(option) {
			this.device.deviceId = option.deviceId
			this.device.lx = option.lx
			this.device.planId = option.planId
			this.addRecord.id = option.recordId
			if (this.addRecord.id != null) {
				this.radioSwitch = false;
				this.textSwitch = false;
				this.runSwitch = false;
				this.uploadSwitch = false;
			}
		},
		onShow() {
			this.getDisAgain()
			document.body.style.overflow = 'auto';
		},
		onUnload() {
			clearInterval(this.intervalId);
		},
		data() {

			return {
				/* 设备 */
				device: {
					deviceId: null,
					lx: null,
					planId: null
				},
				/* 记录体 */
				addRecord: {
					id: null,
					sfyc: null,
					xjfj: null,
					xjms: null
				},
				/* 页面控制 */
				radioSwitch: true,
				textSwitch: true,
				runSwitch: true,
				uploadSwitch: true,
				/* 本地资源 */
				returnUrl: require("../../../static/assets/arrow-left.png"),
				startUrl: require("../../../static/icons/xjyw/play.png"),
				upLoadUrl: require("../../../static/icons/xjyw/add.png"),
				status: 0,
				intervalId: null,
				/* 结果 */
				radioStatus: null,
				resultText: '',
				fileList: [],
				fileNum: null,
				ifOne: false,

				/* 图片暂存列表 */
				fileTempList: [],
				/* 图片格式 */
				ijpeg: 'image/jpeg',
				ipng: 'image/png',
        loading: false
			}
		},
		methods: {
			/* urlStatus(){
				if(this.runSwitch){
					return
				}else{
					if(this.status==0){
						this.getDistance()
						this.intervalId = setInterval(this.getDistance, 10000);
						this.status = 1
						this.startUrl = require("../../../static/icons/xjyw/paused.png")
					}else{
						clearInterval(this.intervalId);
						this.status = 0
						this.startUrl = require("../../../static/icons/xjyw/play.png")
					}
				}
			}, */
			/* 对接文件 */
			getFile() {
				clearInterval(this.intervalId);
				let that = this
				window.croods.customPlugin({
					action: 'ServicePermissionPlugin.uploadMaterial',
					params: {
						reason: "获取相机、文件权限",
						imgCount: "1",
						uploadTitle: "请选择上传方式",
						uploadType: "4",
					},
					success: function(res) {
						let tfile = res.files[0]
						if (res.flag) {
							let temp = tfile.file.replace(/[\r\n]/g, "")
							let url = 'data:' + tfile.type + ';base64,' + temp
							tfile.url = url
							that.fileTempList.push(tfile)
							this.getDisAgain()
						} else {
							that.$u.toast('格式错误，上传失败');
						}
					},
					fail: function(msg) {
						if (msg != null || msg != undefined) {
							that.$u.toast(msg);
						} else {
							that.$u.toast('照片上传失败');
						}
					}
				});
			},
			removeItem(index) {
				this.fileTempList.splice(index, 1);
			},
			/* 定位 */
			getDistance() {
				let temp = this.addRecord.id
				let that = this
				window.croods.customPlugin({
					action: 'ServicePermissionPlugin.getLocation',
					params: {
						reason: '获取定位信息',
						required: 1,
						permissionPurpose: '记录巡检轨迹',
						coorType: 'GCJ02'
					},
					success: function(res) {
						/* alert('经度' + res.longitude + '-' + '纬度' + res.latitude + '位置' + res.locationDescribe) */
						let wgs84Coords = coordtransform.gcj02towgs84(res.longitude, res.latitude);
						let nowDis = {
							id: Number(temp),
							lat: wgs84Coords[1],
							lng: wgs84Coords[0]
						};
						addtrack(nowDis).then(response => {
							/* console.log(response) */
						})
						/* alert(nowDis.id + "-" + nowDis.lng + "-" + nowDis.lat) */
					},
					fail: function(msg) {
						that.$u.toast(msg);
					}
				});
				/* uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						let nowDis = {
							id:this.addRecord.id,
							lat:res.latitude,
							lng:res.longitude
						};
						console.log(nowDis)
						addtrack(nowDis).then(response => {
							console.log(response)
						})
					}
				}); */
			},
			returnPage() {
				uni.navigateBack({
					delta: 1 // 返回上一级页面
				});
			},
			start() {
        if(this.loading) {
          return
        }
        this.loading = true
				addXJRecord(this.device).then(response => {
					if (response.status) {
						this.addRecord.id = response.code
						this.radioSwitch = false;
						this.textSwitch = false;
						this.runSwitch = false;
						this.uploadSwitch = false;
						this.getDistance()
						this.intervalId = setInterval(this.getDistance, 10000);
					} else {
						uni.$u.toast(response.code)
					}
				}).finally(() => {
          this.loading = false
        })
			},
			async submit() {
        if(this.loading) {
          return
        }
				if (this.radioStatus == null) {
					this.$u.toast('巡检情况未选择');
					return;
				}
				if (this.fileTempList.length == 0) {
					this.$u.toast('现场照片未上传');
					return;
				}
				if (this.resultText == "" || this.resultText == null) {
					this.$u.toast('巡检内容未填写');
					return;
				}
				let fj = await this.getIds();
				this.addRecord.xjfj = fj.slice(0, -1);

				this.addRecord.sfyc = this.radioStatus;
				this.addRecord.xjms = this.resultText;

				this.addRecord.id = Number(this.addRecord.id)
				/* alert(JSON.stringify(this.addRecord)) */
        this.loading = true
				editXJRecord(this.addRecord).then(response => {
					this.$u.toast('提交成功');
					setTimeout(function() {
						uni.navigateBack({
							delta: 1
						});
					}, 1000);
					/* console.log(response) */
				}).finally(() => {
          this.loading = false
        })

				/* this.returnPage() */

			},
			async getIds() {
				let fj = '';
				let promises = this.fileTempList.map(async item => {
					let temp = {
						bizType: "app",
						file: item.file,
						fileName: item.name,
						fileType: item.type
					}
					let res = await uploadFile(temp);
					fj += res.id + ';'
				})
				await Promise.all(promises);
				return fj;
			},
			getDisAgain() {
				if (this.addRecord.id !== '') {
					this.intervalId = setInterval(this.getDistance, 10000);
				}
			}
		},
		mounted() {

		},
	}
</script>

<style>
	.main {
		background-color: #FAFAFA;
		width: 100vw;
		height: 80vh;
		overflow-y: hidden;
	}
</style>